package androidjniapi

import (
	"encoding/json"
	"fmt"
	"os"
	"vpn/guard/config"
	"vpn/guard/device"
)

var globalVpnService *device.Device

func Start(fd int32, cfg string) string {
	if globalVpnService != nil {
		fmt.Println("stop old")
		Stop()
	}
	var cfg_ config.Config
	err := json.Unmarshal([]byte(cfg), &cfg_)
	fmt.Println("cfg_:", cfg_)
	if err != nil {
		fmt.Println("配置信息不是标准json str", err)
		return "配置信息不是标准json str"
	}
	tunFile := os.NewFile(uintptr(fd), "")
	deviceTun := &device.DeviceTunnel{
		Read: func(data []byte) (int, error) {
			return tunFile.Read(data)
		},
		Write: func(data []byte) (int, error) {
			return tunFile.Write(data)
		},
		Close: func() error {
			tunFile.Close()
			tunFile = nil
			return nil
		},
		Name: func() string {
			return cfg_.TunName
		},
		Mtu: func() int {
			return cfg_.Mtu
		},
	}
	globalVpnService = device.NewDevice(device.NewDeviceParams{
		Tun:    deviceTun,
		Config: &cfg_,
	})
	fmt.Println("start ok1")
	globalVpnService.UpDevice()
	fmt.Println("start ok2")
	return ""
}

func Stop() {
	if globalVpnService != nil {
		globalVpnService.DownDevice()
		globalVpnService = nil
	}
}
